import React, { useState } from 'react';
import { Space, Tag, Button, message, Modal, Card, Switch, Popover, Tooltip } from 'antd';
import { UserOutlined, EditOutlined, DeleteOutlined, EyeOutlined, SettingOutlined, PushpinOutlined, SearchOutlined, ColumnWidthOutlined, MenuOutlined } from '@ant-design/icons';
import AdvancedTable from '@/components/common/AdvancedTable/AdvancedTable';
import { useTable } from '@/components/common/AdvancedTable/useTable';

// 模拟数据类型
interface UserData {
  id: number;
  username: string;
  name: string;
  email: string;
  phone: string;
  status: 'active' | 'inactive' | 'pending';
  role: 'admin' | 'user' | 'moderator';
  department: string;
  createTime: string;
  lastLoginTime: string;
  avatar?: string;
}

// 模拟 API 调用
const fetchUserData = async (params: any) => {

  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1000));

  // 模拟数据
  const mockData: UserData[] = Array.from({ length: 100 }, (_, index) => ({
    id: index + 1,
    username: `user${index + 1}`,
    name: `用户${index + 1}`,
    email: `user${index + 1}@example.com`,
    phone: `138${String(index).padStart(8, '0')}`,
    status: ['active', 'inactive', 'pending'][Math.floor(Math.random() * 3)] as any,
    role: ['admin', 'user', 'moderator'][Math.floor(Math.random() * 3)] as any,
    department: ['技术部', '市场部', '运营部', '人事部'][Math.floor(Math.random() * 4)],
    createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
    lastLoginTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
  }));

  // 应用搜索过滤
  let filteredData = mockData;
  if (params.search) {
    if (params.search.username) {
      filteredData = filteredData.filter(item => item.username.includes(params.search.username));
    }
    if (params.search.status) {
      filteredData = filteredData.filter(item => item.status === params.search.status);
    }
    if (params.search.role) {
      filteredData = filteredData.filter(item => item.role === params.search.role);
    }
    if (params.search.department) {
      filteredData = filteredData.filter(item => item.department === params.search.department);
    }
  }

  // 应用排序
  if (params.sort) {
    filteredData.sort((a, b) => {
      const aValue = a[params.sort.field as keyof UserData];
      const bValue = b[params.sort.field as keyof UserData];

      if (typeof aValue === 'string' && typeof bValue === 'string') {
        return params.sort.order === 'ascend'
          ? aValue.localeCompare(bValue)
          : bValue.localeCompare(aValue);
      }

      if (typeof aValue === 'number' && typeof bValue === 'number') {
        return params.sort.order === 'ascend' ? aValue - bValue : bValue - aValue;
      }

      return 0;
    });
  }

  // 分页
  const start = (params.page - 1) * params.pageSize;
  const end = start + params.pageSize;
  const pageData = filteredData.slice(start, end);

  return {
    data: pageData,
    total: filteredData.length,
    page: params.page,
    pageSize: params.pageSize,
  };
};

const AdvancedTableDemo: React.FC = () => {
  // 控制功能的状态
  const [stickyHeader, setStickyHeader] = useState(true);
  const [columnPinningEnabled, setColumnPinningEnabled] = useState(true);
  const [columnSettingsEnabled, setColumnSettingsEnabled] = useState(true);
  const [showColumnsPopover, setShowColumnsPopover] = useState(false);

  const table = useTable<UserData>({
    queryKey: 'users',
    fetchData: fetchUserData,
    defaultPageSize: 10,
    defaultSort: {
      field: 'createTime',
      order: 'descend',
    },
    searchFields: [
      {
        key: 'username',
        label: '用户名',
        type: 'input',
        placeholder: '请输入用户名',
      },
      {
        key: 'status',
        label: '状态',
        type: 'select',
        options: [
          { label: '激活', value: 'active' },
          { label: '禁用', value: 'inactive' },
          { label: '待审核', value: 'pending' },
        ],
      },
      {
        key: 'role',
        label: '角色',
        type: 'select',
        options: [
          { label: '管理员', value: 'admin' },
          { label: '普通用户', value: 'user' },
          { label: '版主', value: 'moderator' },
        ],
      },
      {
        key: 'department',
        label: '部门',
        type: 'select',
        options: [
          { label: '技术部', value: '技术部' },
          { label: '市场部', value: '市场部' },
          { label: '运营部', value: '运营部' },
          { label: '人事部', value: '人事部' },
        ],
      },
    ],
    onSuccess: (data) => {
      // 数据获取成功
    },
    onError: (error) => {
      // 数据获取失败
      message.error('数据加载失败');
    },
  });

  // 定义表格列
  const columns = [
    {
      key: 'id',
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      sorter: true,
    },
    {
      key: 'username',
      title: '用户名',
      dataIndex: 'username',
      width: 120,
      sorter: true,
      render: (text: string, record: UserData) => (
        <Space>
          <UserOutlined />
          {text}
        </Space>
      ),
    },
    {
      key: 'name',
      title: '姓名',
      dataIndex: 'name',
      width: 120,
      sorter: true,
    },
    {
      key: 'email',
      title: '邮箱',
      dataIndex: 'email',
      width: 200,
      ellipsis: true,
    },
    {
      key: 'phone',
      title: '手机号',
      dataIndex: 'phone',
      width: 140,
    },
    {
      key: 'status',
      title: '状态',
      dataIndex: 'status',
      width: 100,
      filters: [
        { text: '激活', value: 'active' },
        { text: '禁用', value: 'inactive' },
        { text: '待审核', value: 'pending' },
      ],
      filterMultiple: true,
      render: (status: string) => {
        const statusMap = {
          active: { color: 'green', text: '激活' },
          inactive: { color: 'red', text: '禁用' },
          pending: { color: 'orange', text: '待审核' },
        };
        const config = statusMap[status as keyof typeof statusMap];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      key: 'role',
      title: '角色',
      dataIndex: 'role',
      width: 100,
      filters: [
        { text: '管理员', value: 'admin' },
        { text: '普通用户', value: 'user' },
        { text: '版主', value: 'moderator' },
      ],
      render: (role: string) => {
        const roleMap = {
          admin: { color: 'red', text: '管理员' },
          user: { color: 'blue', text: '普通用户' },
          moderator: { color: 'purple', text: '版主' },
        };
        const config = roleMap[role as keyof typeof roleMap];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      key: 'department',
      title: '部门',
      dataIndex: 'department',
      width: 120,
      filters: [
        { text: '技术部', value: '技术部' },
        { text: '市场部', value: '市场部' },
        { text: '运营部', value: '运营部' },
        { text: '人事部', value: '人事部' },
      ],
    },
    {
      key: 'createTime',
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
      sorter: true,
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      key: 'lastLoginTime',
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      width: 180,
      sorter: true,
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      key: 'actions',
      title: '操作',
      dataIndex: 'actions',
      width: 180,
      render: (text: any, record: UserData) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => {
              Modal.info({
                title: '用户详情',
                content: (
                  <div>
                    <p>用户名: {record.username}</p>
                    <p>姓名: {record.name}</p>
                    <p>邮箱: {record.email}</p>
                    <p>手机: {record.phone}</p>
                    <p>状态: {record.status}</p>
                    <p>角色: {record.role}</p>
                    <p>部门: {record.department}</p>
                  </div>
                ),
              });
            }}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => message.info(`编辑用户: ${record.username}`)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => {
              Modal.confirm({
                title: '确认删除',
                content: `确定要删除用户 ${record.username} 吗？`,
                onOk: () => {
                  table.handleDelete([record.id]);
                  message.success('删除成功');
                },
              });
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 批量操作
  const batchActions = [
    {
      key: 'batchDelete',
      label: '批量删除',
      icon: <DeleteOutlined />,
      danger: true,
      onClick: (selectedRows: UserData[]) => {
        Modal.confirm({
          title: '确认批量删除',
          content: `确定要删除选中的 ${selectedRows.length} 个用户吗？`,
          onOk: () => {
            const ids = selectedRows.map(row => row.id);
            table.handleDelete(ids);
            message.success(`成功删除 ${selectedRows.length} 个用户`);
          },
        });
      },
    },
    {
      key: 'batchActivate',
      label: '批量激活',
      onClick: (selectedRows: UserData[]) => {
        message.success(`已激活 ${selectedRows.length} 个用户`);
      },
    },
  ];

  // 渲染列显示的内容
  const renderColumnsContent = () => {
    return (
      <div style={{ minWidth: 200 }}>
        <h4 style={{ margin: '0 0 12px 0', fontWeight: 'bold' }}>列显示控制</h4>
        <div style={{ marginBottom: 12 }}>
          <Space direction="vertical" size="small" style={{ width: '100%' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span>固定表头</span>
              <Switch
                size="small"
                checked={stickyHeader}
                onChange={setStickyHeader}
                checkedChildren="开"
                unCheckedChildren="关"
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span>列固定功能</span>
              <Switch
                size="small"
                checked={columnPinningEnabled}
                onChange={setColumnPinningEnabled}
                checkedChildren="开"
                unCheckedChildren="关"
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span>列设置功能</span>
              <Switch
                size="small"
                checked={columnSettingsEnabled}
                onChange={setColumnSettingsEnabled}
                checkedChildren="开"
                unCheckedChildren="关"
              />
            </div>
          </Space>
        </div>

        <div>
          <h5 style={{ margin: '12px 0 8px 0', fontSize: 12, color: '#666' }}>当前固定列</h5>
          <div style={{ fontSize: 12 }}>
            <div style={{ marginBottom: 4, color: '#999' }}>
              暂无固定列，请通过表格上方的"列固定"功能设置
            </div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div style={{ padding: 24, height: 'calc(100vh - 180px)', display: 'flex', flexDirection: 'column' }}>
      <Card
        title={
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span>高级表格演示 - 功能控制面板</span>
            <Space>
              <Popover
                content={renderColumnsContent()}
                title="表格功能控制"
                trigger="click"
                open={showColumnsPopover}
                onOpenChange={setShowColumnsPopover}
                placement="bottomRight"
              >
                <Button
                  type="primary"
                  icon={<SettingOutlined />}
                  size="small"
                >
                  功能设置
                </Button>
              </Popover>
            </Space>
          </div>
        }
        style={{ flex: 1, display: 'flex', flexDirection: 'column' }}
        bodyStyle={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}
      >
        <AdvancedTable<UserData>
          columns={columns}
          dataSource={table.data}
          loading={table.loading}
          pagination={table.pagination}
          searchFields={table.searchFields}
          onSearch={table.handleSearch}
          onExport={table.exportData}
          refresh={table.refresh}
          batchActions={batchActions}
          columnSettings={{
            enabled: columnSettingsEnabled,
            defaultVisibleColumns: columns.map(col => col.key),
            onColumnsChange: (visibleColumns) => {
              // 可见列变化处理
            },
          }}
          columnPinning={{
            enabled: columnPinningEnabled,
            defaultPinnedColumns: {
              left: [],
              right: [],
            },
            onPinnedColumnsChange: (pinnedColumns) => {
              // 列固定变化处理
            },
          }}
          stickySettings={{
            enabled: stickyHeader,
            header: stickyHeader,
            offsetTop: 64, // 距离顶部 64px
          }}
          scroll={{ x: 1400 }} // 只设置横向滚动，纵向使用外层滚动
          title={() => (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
              <span>高级表格演示</span>
              <Space>
                <Tooltip title="切换固定表头">
                  <Button
                    type={stickyHeader ? 'primary' : 'default'}
                    size="small"
                    icon={<PushpinOutlined />}
                    onClick={() => setStickyHeader(!stickyHeader)}
                  >
                    表头
                  </Button>
                </Tooltip>
                <Tooltip title="切换列固定">
                  <Button
                    type={columnPinningEnabled ? 'primary' : 'default'}
                    size="small"
                    icon={<ColumnWidthOutlined />}
                    onClick={() => setColumnPinningEnabled(!columnPinningEnabled)}
                  >
                    列固定
                  </Button>
                </Tooltip>
                <Tooltip title="显示列信息">
                  <Button
                    type={columnSettingsEnabled ? 'primary' : 'default'}
                    size="small"
                    icon={<MenuOutlined />}
                    onClick={() => setShowColumnsPopover(!showColumnsPopover)}
                  >
                    列信息
                  </Button>
                </Tooltip>
              </Space>
            </div>
          )}
          onChange={table.handleTableChange}
          rowSelection={{
            type: 'checkbox',
            onChange: (selectedRowKeys, selectedRows) => {
              // 行选择变化处理
            },
          }}
          rowClassName={(record, index) => {
            return index % 2 === 0 ? 'even-row' : 'odd-row';
          }}
          onRow={(record, index) => {
            return {
              onClick: (event) => {
                // 行点击处理
              },
              onDoubleClick: (event) => {
                // 行双击处理
              },
            };
          }}
        />
      </Card>
    </div>
  );
};

export default AdvancedTableDemo;